package org.example.symbol;



import java.util.Iterator;

public class SymbolTable<Key extends Comparable<Key>, Value> implements Iterable{
    @Override
    public Iterator iterator() {
        return null;
    }
    public class SIerator implements Iterator{
        private Node node;
        public SIerator(){
            this.node=head.next;
        }

        @Override
        public boolean hasNext() {
            return node.next!=null;
        }

        @Override
        public Object next() {
            node=node.next;
            return node;
        }
    }

    public class Node {
        private Key key;
        private Value value;
        private Node next;

        public Node() {
        }

        public Node(Key key, Value value, Node next) {
            this.key = key;
            this.value = value;
            this.next = next;
        }
    }

    private Node head;
    private int N;

    public SymbolTable() {
        this.head = null;
        this.N = 0;
    }

    public Value get(Key key) {
        Node node = head;
        for (int i = 0; node.next != null; i++) {
            node = node.next;
            if (node.key.equals(key)) {
                return node.value;
            }
        }
        return null;
    }

    public void put(Key key, Value value) {
        Node node = new Node(key, value, null);
        Node curr = head.next;
        Node pre = head;
        if (head.next == null) {
            head.next = node;
        }
        while (curr!=null&&key.compareTo(curr.key)>0){
            pre=curr;
            curr=curr.next;
        }
        if (curr.key.equals(key)){
            curr.value=value;
        }
        pre.next = node;
        node.next=curr;
        N++;
    }

    public void delete(Key key) {
        Node node = head;
        for (int i = 0; node.next != null; i++) {
            if (node.next.key.equals(key)) {
                node.next = node.next.next;
                node.next.next = null;
                N--;
                return;
            }
            node = node.next;
        }
    }

    public int size() {
        return N;
    }
}
